<!-- <FileUpload :files="formConfig.formData.strChilds" :path="state.path" action="upload"
	:params="{ sourceCd: 'crm_fw_img' }" /> -->
<!-- import FileUpload from '@/components/FileUpload/index.vue' -->

<template>
	<van-uploader v-model="state.fileList" :before-read="handleBeforeRead" :after-read="afterRead"
		@oversize="handleOversize" v-bind="$attrs" :maxSize="maxSize" :accept="accept" :disabled="disabled" />
</template>

<script setup lang="ts">
	import { ref, reactive, watch, nextTick } from 'vue';
	import { commonPostBob } from '@/api/common/baseApi'
	import { showToast } from 'vant';
	import { addWatermark } from '@/utils/watermark';

	const props = withDefaults(defineProps<{
		files : any
		path : string // contraller路径
		action : string // 方法
		params ?: Record<string, any>  //额外参数
		maxSize ?: number // 默认5MB
		maxCount ?: number
		accept ?: string // 允许的文件类型
		disabled ?: boolean // 是否禁用
		needWaterMark ?: boolean // 是否需要水印
		waterMarkConfig ?: Record<string, any> //水印配置参数
	}>(), {
		path: '',
		action: '',
		params: {} as any,
		maxSize: 5 * 1024 * 1024,
		accept: 'image/*',
		disabled: false,
	})

	const emit = defineEmits(['oversize', 'update:files'])

	const state = reactive({
		fileList: [] as any
	})

	// 文件大小超出限制
	const handleOversize = (file : any) => {
		emit('oversize', file);
		showToast(`文件大小不能超过${props.maxSize / 1024 / 1024}MB`);
	};

	// 文件读取前处理
	const handleBeforeRead = (file : any) => {

		// 检查文件类型
		if (props.accept && !file.type.match(new RegExp(props.accept.replace('*', '.*')))) {
			showToast(`请上传${props.accept}格式的文件`);
			return false;
		}

		// 检查文件大小
		if (file.size > props.maxSize) {
			emit('oversize', file);
			showToast(`文件大小不能超过${props.maxSize / 1024 / 1024}MB`);
			return false;
		}

		return true;
	};

	// 上传
	const afterRead = async ({ file } : any) => {

		// 先移除自动添加的文件（避免重复）
		state.fileList = state.fileList.filter((f : any) => { file.name !== f.name });

		// blob 对象
		let blobObj : any
		// 缩略图的url
		let previewUrl : any;
		// 最终需要上传的file对象
		let paramsFile : any

		if (props.needWaterMark) {
			// 添加水印
			blobObj = await addWatermark(file, props.waterMarkConfig);
			paramsFile = new File([blobObj], file.name, {
				type: 'image/jpeg',
				lastModified: Date.now()
			});
		} else {
			blobObj = new Blob([file], { type: file.type });
			paramsFile = file
		}

		// 生成预览
		previewUrl = URL.createObjectURL(blobObj);

		const formData = new FormData()
		formData.append('file', paramsFile)

		// 添加额外参数
		if (props['params']) {
			Object.keys(props['params']).forEach(d => {
				formData.append(d, props['params'][d])
			})
		}
		commonPostBob(props.path, props.action, formData).then((res : any) => {
			if (res.data.code === 200) {
				const result = res.data.result
				state.fileList.push({ url: previewUrl, isImage: true, urlId: result, name: file.name })
				emit('update:files', state.fileList);
			}
		})
	};

	const resetFiles = () => {
		state.fileList.splice(0, state.fileList.length)
	}

	defineExpose({ resetFiles })
</script>

<style>
</style>